package com.controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.entities.Account;
import com.service.AccountService;
import com.util.GetFileName;

@Controller
@SessionAttributes(types = {Account.class})
@RequestMapping(value = "/account")
public class AccountController {

	@Reference
	private AccountService accountService;
	
	@ResponseBody
	@RequestMapping(value = "/login")
	public boolean login(String accountName,String accountPassword ,Map<String, Object> map) {
		Account account= this.accountService.loginAccount(accountName, accountPassword);
		if(null != account) {
			map.put("account", account);
			return true;
		}else {
			return false;
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/checkAccountName")
	public boolean checkAccount(String accountName) {
		return this.accountService.checkAccountName(accountName);
	}
	
	@ResponseBody
	@RequestMapping(value = "/checkPhone")
	public boolean checkPhone(String phone) {
		return this.accountService.checkPhone(phone);
	}
	
	@ResponseBody
	@RequestMapping(value = "/checkIdCard")
	public boolean checkIdCard(String idCard) {
		return this.accountService.checkIdCard(idCard);
	}
	
	@ResponseBody
	@RequestMapping(value = "/register")
	public boolean register(MultipartFile[] file,HttpSession session ,HttpServletRequest request,Account account) throws Exception, IOException {
		MultipartFile file1=file[0];
		String fileName="";
		if(file1!=null) {
			String []s=file1.getOriginalFilename().split("\\.");
			String ext=s[1];
			fileName=GetFileName.getFilName(request)+"."+ext;
			File newFile=new File(session.getServletContext().getRealPath("/IdCardImg")+File.separator+fileName);
			file1.transferTo(newFile);
			account.setCardPicture("/IdCardImg/"+fileName);
		}
		MultipartFile file2=file[1];
		if(file2!=null) {
			String []s=file2.getOriginalFilename().split("\\.");
			String ext=s[1];
			fileName=GetFileName.getFilName(request)+"."+ext;
			File newFile=new File(session.getServletContext().getRealPath("/HeadPicture")+File.separator+fileName);
			file2.transferTo(newFile);
			account.setHeadPortrait("/HeadPicture/"+fileName);
		}
		return this.accountService.registerAccount(account);
	}
}
